#include <stdio.h>
#include <stdlib.h>
#include <time.h>


#define DL 3
#define STR(n) #n
#define DIGIT_LEN_STR(n) "%" STR(n) "d"

typedef struct note
{
    int data;
    struct note *next;
} note_t;

note_t * get_new_note(int val)
{
    note_t *p = (note_t *)malloc(sizeof(note_t));
    p->data = val;
    p->next = NULL;
    return p;
}

note_t * insert_note(note_t *head, int postion, int val)
{
    if (postion == 0)
    {
        note_t *p = get_new_note(val);
        p->next = head;
        return p;
    }
    note_t *p = head;
    note_t *new_note = get_new_note(val);
    for (int i = 1; i < postion; i++)
    {
        p = p->next;
    }
    new_note->next = p->next;
    p->next = new_note;
    return head;
}

void output_linklist(note_t *head, int flag = 0) {
    int n = 0;
    for (note_t *p = head; p; p = p->next) n += 1;
    for (int i = 0; i < n; i++) {
        printf(DIGIT_LEN_STR(DL), i);
        printf("  ");
    }
    printf("\n");
    for (note_t *p = head; p; p = p->next) {
        printf(DIGIT_LEN_STR(DL), p->data);
        printf("->");
    }
    printf("\n");
    if (flag == 0) printf("\n\n");
    return ;
}

void clear_linklist(note_t *linklist)
{
    if (linklist == NULL)
        return;
    for (note_t *p = linklist, *q; p ; p = q)
    {
        q = p->next;
        free(p);
    }
}

int main()
{
    srand(time(0));
    #define MAX_OP 7
    note_t *head = NULL;
    for (int i = 0; i < MAX_OP; i++) {
        int pos = rand() % (i + 1), val = rand() % 100;
        printf("insert %d at %d to linklist\n", val, pos);
        head = insert_note(head, pos, val);
        output_linklist(head);
    }
    clear_linklist(head);
    return 0;
}
